// const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const routes = require('./routes')
const pkg = require('./package')
const formidable = require('express-formidable')
const config = require('config-lite')(__dirname)
const winston = require('winston')
const expressWinston = require('express-winston')
const app = express()
const { sequelize } = require('./common/sequelize')

// 设置模板目录
// app.set('views', path.join(__dirname, 'views'));
// 设置模板引擎为 jade
// app.set('view engine', 'jade');

// 设置静态文件夹
app.use(express.static(path.join(__dirname, 'public')))
// json请求的支持
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())

// 处理表单及文件上传的中间件
app.use(formidable({
  uploadDir: path.join(__dirname, 'public/images'), // 上传文件目录
  keepExtensions: true// 保留后缀
}))

// 错误处理器
app.use(function(err, req, res, next) {
  console.error(err)
})
// 正常请求的日志
app.use(expressWinston.logger({
  transports: [
    new (winston.transports.Console)({
      json: true,
      colorize: true
    }),
    new winston.transports.File({
      filename: 'logs/success.log'
    })
  ]
}))
// 路由
routes(app)
// 错误请求的日志
app.use(expressWinston.errorLogger({
  transports: [
    new winston.transports.Console({
      json: true,
      colorize: true
    }),
    new winston.transports.File({
      filename: 'logs/error.log'
    })
  ]
}))

if (module.parent) {
  // 被 require，则导出 app
  module.exports = app
} else {
  // 监听端口，启动程序
  sequelize.authenticate().then(() => {
    console.log(sequelize.models)
    app.listen(config.port, () => {
      console.log(`${pkg.name} listening on port ${config.port}`)
    })
  }).catch((error) => {
    console.log(error.message)
  })
}
